using AutoMapper;
using Microsoft.EntityFrameworkCore;
using ShopForWeb.Dto.ViewModels;
using ShopForWeb.Models;

namespace ShopForWeb.Service;
public class ManagerService
{
  private ShopDbContext _context;
  private IMapper _mapper;
  public ManagerService(ShopDbContext context, IMapper mapper)
  {
    _context = context;
    _mapper = mapper;
  }
  //查
  public async Task<List<ManagerViewModel>> GetByPageAsync(int skip, int take, string key)
  {
    var mangers = await _context.Managers
                                  .Where(m => EF.Functions.Like(m.Name, $"%{key}%"))
                                  .OrderByDescending(m => m.ManagerID)
                                 .Skip(skip)
                                 .Take(take)
                                 .AsNoTracking()
                                 .ToListAsync();
    // return _mapper.Map<List<ManagerViewModel>>(mangers);
    return _mapper.Map<List<ManagerViewModel>>(mangers);
  }
  public async Task<int> GetCountAsync(string key)
  {
    return await _context.Managers
                          .Where(m => EF.Functions.Like(m.Name, $"%{key}%"))
                          .CountAsync();
  }
  //新增
  public async Task<int> AddNewAsync(ManagerViewModel pvm)
  {
    var m = _mapper.Map<Manager>(pvm);
    _context.Entry<Manager>(m).State = EntityState.Added;
    return await _context.SaveChangesAsync();
  }
  //修改
  public async Task<ManagerViewModel?> GetByIDAsync(int ManagerID)
  {
    var m = await _context.Managers.Where(m => m.ManagerID == ManagerID)
     .FirstOrDefaultAsync();
    if (m == null) return null;
    return _mapper.Map<ManagerViewModel>(m);
  }
  public async Task<int> ModifyAsync(ManagerViewModel pvm)
  {
    var m = _mapper.Map<Manager>(pvm);
    _context.Entry<Manager>(m).State = EntityState.Modified;
    return await _context.SaveChangesAsync();
  }
  //删除
  public async Task<int> RemoveAsync(int managerID)
  {
    _context.Managers.Remove(new Manager()
    {
      ManagerID = managerID
    });
    return await _context.SaveChangesAsync();
  }

  public async Task<ManagerViewModel?> GetByLoginAsync(string phone, string password)
  {
    var m = await _context.Managers.Where(m => m.Phone == phone && m.Password == password)
                             .FirstOrDefaultAsync();
    if (m == null)
      return null;
    return _mapper.Map<ManagerViewModel>(m);
  }



}
